import  {
    createSlice
} from "@reduxjs/toolkit";
import {useSelector} from "react-redux";
import {getFindByParentId} from "@/api/dict";
const findInfo:any = (arr: any, id:number) => {
    let info;
    for (let i =0; i < arr.length; i++) {
        if (arr[i].id == id) {
            info = arr[i]
        } else if (arr[i].children && arr[i].children.length > 0) {
            info = findInfo(arr[i].children, id)
        }
        if (info) {
            break;
        }
    }
    return info;
}
const dictSlice = createSlice({
    name: 'dict',
    initialState: {
        dictList: [],
        // 1- 增加loading 状态
        loading:false
    },
    reducers: {
        /*思路：
   * 1- 根据省份ID,可以获得省份下的类别
   * 2- 获取到省份下的类别后，需要将数据作为省份对象下的children属性值
   * */
        upDictList(state, {payload}) {
            const {dictList, id} = payload
            // console.log(dictList, id);
            // const info = state.dictList.find((v:any) => v.id === id);
            const info = findInfo(state.dictList, id)
            // console.log(info, '----')
            if (info) {
                info.children = dictList;
            }else {
                state.dictList = dictList;
            }

        },
        // 2- 增加修改loading方法
        upLoading(state,{payload}){
            state.loading = payload;
        },
    }
})
const {upDictList, upLoading} = dictSlice.actions;

export const getFindByParentIdAysnc = (id: number) => {
    return async (dispatch: any) => {
        dispatch(upLoading(true));
        const result = await getFindByParentId(id);
        // console.log(result,'0000')
        dispatch(upDictList(
            {
                dictList: result.data.map((item:any) => {
                    if (item.hasChildren) item.children = [];
                    return item;
                }),
                id
            }
        ))
        dispatch(upLoading(false));
    }
}
export const useSelectDict = () => useSelector((state: any) => state.dict)
export default dictSlice.reducer;
